import React, { createContext, useContext, useReducer } from 'react';
import { AppState, AppAction } from '../types/types';
import { DEFAULT_NETWORKS } from '../utils/networkUtils';

const initialState: AppState = {
    abi: '',
    methods: [],
    contractAddress: '',
    networks: DEFAULT_NETWORKS,
    currentNetwork: DEFAULT_NETWORKS[0],
    customRpc: ''
};

function appReducer(state: AppState, action: AppAction): AppState {
    switch (action.type) {
        case 'SET_ABI':
            return { ...state, abi: action.payload };
        case 'SET_METHODS':
            return { ...state, methods: action.payload };
        case 'SET_CONTRACT_ADDRESS':
            return { ...state, contractAddress: action.payload };
        case 'SET_CURRENT_METHOD':
            return { ...state, currentMethod: action.payload };
        case 'SET_RESULT':
            return { ...state, result: action.payload, error: undefined };
        case 'SET_ERROR':
            return { ...state, error: action.payload, result: undefined };
        case 'SET_NETWORK':
            return { ...state, currentNetwork: action.payload };
        case 'SET_CUSTOM_RPC':
            return { ...state, customRpc: action.payload };
        default:
            return state;
    }
}

const AppContext = createContext<{
    state: AppState;
    dispatch: React.Dispatch<AppAction>;
}>({
    state: initialState,
    dispatch: () => null
});

export const AppProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
    const [state, dispatch] = useReducer(appReducer, initialState);

    return (
        <AppContext.Provider value={{ state, dispatch }}>
            {children}
        </AppContext.Provider>
    );
};

export const useAppContext = () => useContext(AppContext);